﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace AutomaticPush.Extension
{
    public class LogHelper
    { 
        private static readonly object o = new { };

        /// <summary>
        /// 记录日志(本地文件)
        /// </summary>
        /// <param name="errMsg"></param>
        public static void WriteLog(string errMsg)
        {
            WriteLog("WriteLog", errMsg, "Log");
        }

        /// <summary>
        /// 记录错误日志
        /// </summary>
        /// <param name="funName">执行方法名</param>
        /// <param name="msg">日志内容信息</param>
        /// <param name="logType">日志类型</param>
        public static void WriteLog(string funName, string msg, string logType = "ErrLog", string fileType = "")
        {
            try
            {
  
                {
                    string errorTxt = "";
                    string fileDirectory = "";
                    string fileName = "";
                    string logName = "";
                    logName = fileType + (string.IsNullOrEmpty(fileType) ? "" : "_") + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    if (string.IsNullOrEmpty(fileType))
                        fileDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\" + logType;
                    else
                    {
                        fileDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\" + logType + $@"\{DateTime.Now.ToString("yyyyMMdd")}";
                    }
                    fileName = fileDirectory + "\\" + logName;


                    lock (o)
                    {
                        try
                        {
                            if (!Directory.Exists(fileDirectory))
                                Directory.CreateDirectory(fileDirectory);
                            if (!File.Exists(fileName))
                            {
                                StreamWriter sw;
                                sw = File.CreateText(fileName);
                                sw.Close();
                            }
                            errorTxt = Convert.ToString(Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss")) + " : 方法名：" + funName + "，日志内容：" + msg
                                + Environment.NewLine;
                            File.AppendAllText(fileName, errorTxt);

                            //Task.Run(() => { DeleteFile(ConfigManage.GetWebSiteConfigByAppKey("DeleteLog"), logType); });

                        }
                        catch
                        {
                            //
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string errorTxt = "";
                string logName = fileType + (string.IsNullOrEmpty(fileType) ? "" : "_") + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                string fileDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\" + logType;
                string fileName = fileDirectory + "\\" + logName;
                lock (o)
                {
                    try
                    {
                        if (!Directory.Exists(fileDirectory))
                            Directory.CreateDirectory(fileDirectory);
                        if (!File.Exists(fileName))
                        {
                            StreamWriter sw;
                            sw = File.CreateText(fileName);
                            sw.Close();
                        }
                        errorTxt = Convert.ToString(Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss")) + " : 方法名：" + funName + "，日志内容：" + msg
                            + Environment.NewLine;
                        File.AppendAllText(fileName, errorTxt);
                    }
                    catch
                    {
                        //
                    }
                }
            }
        }
        /// <summary>
        /// 删除文件夹和文件
        /// </summary>
        /// <param name="fileDirect"></param>
        /// <param name="saveDay"></param>
        public static void DeleteFile(string saveDay, string fileDirect = "", bool flag = false)
        {
            DateTime nowTime = DateTime.Now;
            //string str = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\');
            //string text2 = str + "/App_Data/" + fileDirect + "/";
            DirectoryInfo root = new DirectoryInfo(fileDirect);
            var dics = root.GetDirectories();
            var dicsFiles = root.GetFiles();
            FileAttributes attr = File.GetAttributes(fileDirect);
            if (attr == FileAttributes.Directory)
            {
                if (flag)
                {
                    foreach (DirectoryInfo file in dics)
                    {
                        if (file.CreationTime < DateTime.Now.AddDays(Convert.ToInt32("-" + saveDay)))
                        {
                            Directory.Delete(file.FullName, true);
                        }
                    }
                }
                else
                {
                    foreach (var file in dicsFiles)
                    {
                        if (file.CreationTime < DateTime.Now.AddDays(Convert.ToInt32(saveDay) * -1))
                        {
                            file.Delete();
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 记录请求参数
        /// </summary>
        /// <param name="FunctionName">方法名称</param>
        /// <param name="detial">细节</param>
        public static void WriteRequstPar(string FunctionName, object detial)
        {
            string errorTxt = "";
            //string fileDirectory = HttpContext.Current.Server.MapPath("/App_Data/");
            string fileDirectory = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/";
            string logName = DateTime.Now.ToString("yyyyMMdd") + "requestPar.txt";
            string fileName = fileDirectory + logName;
            try
            {
                if (!Directory.Exists(fileDirectory))
                {
                    Directory.CreateDirectory(fileDirectory);
                }
                if (!File.Exists(fileName))
                {

                    StreamWriter sw;
                    sw = File.CreateText(fileName);
                    sw.Close();

                }
                errorTxt = Convert.ToString(Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss")) + "  方法名：" + FunctionName + "， 请求参数：" + JsonSerializer.Serialize(detial) + Environment.NewLine;
                File.AppendAllText(fileName, errorTxt);

            }
            catch
            {
                //
            }
        }



 
    }
}
